

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class ChessView extends JPanel {
	int sx = 20, sy = 20, unit = 30;

	public ChessView() {
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				int x = e.getX();
				int y = e.getY();
				int row = (y - sy) / unit;
				int col = (x - sx) / unit;
				if ((y - sy) % unit > unit / 2) {
					row++;
				}
				if ((x - sx) % unit > unit / 2) {
					col++;
				}
				Constants.cont.pressMouseOnChessPanel(row, col);
			}
		});
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		drawChessPanel(g);
		drawChess(g);
	}

	private void drawChess(Graphics g) {
		for (int row = 0; row < ChessModel.WIDTH; row++) {
			for (int col = 0; col < ChessModel.WIDTH; col++) {
				int color = Constants.model.getChess(row, col);
				if (color == Constants.model.BLACK) {
					g.setColor(Color.black);
					drawTrueChess(row,col,g);
				} else if (color == Constants.model.WHITE) {
					g.setColor(Color.white);
					drawTrueChess(row,col,g);
				}
			}
		}
	}

	private void drawTrueChess(int row, int col, Graphics g) {
		int x1 = sx + col*unit - unit/2;
		int y1  = sy + row*unit -unit/2;
		g.fillOval(x1, y1, unit, unit);
	}

	private void drawChessPanel(Graphics g) {
		g.setColor(Color.black);
		for (int i = 0; i < ChessModel.WIDTH; i++) {
			g.drawLine(sx, sy + unit * i, sx + (ChessModel.WIDTH - 1) * unit,
					sy + unit * i);
			g.drawLine(sx + unit * i, sy, sx + unit * i, sy
					+ (ChessModel.WIDTH - 1) * unit);
		}
	}

}
